package com.blacktry.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.blacktry.entity.easypoidata.DeriveExcel;
import com.blacktry.entity.model.Admin;
import com.blacktry.entity.model.ExamManage;
import com.blacktry.entity.model.request.ExamRequest;
import com.blacktry.entity.model.request.ScoreRequest;
import com.blacktry.entity.model.request.StudentRequest;
import com.blacktry.mapper.ExamManageMapper;
import com.blacktry.service.CourseDistributionService;
import com.blacktry.service.DeriveExcelService;
import com.blacktry.service.ExamManageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 考试管理表 服务实现类
 * </p>
 *
 * @author blackTry
 * @since 2021-06-24
 */
@Service
public class ExamManageServiceImpl extends ServiceImpl<ExamManageMapper, ExamManage> implements ExamManageService {

    @Override
    public Integer insert(ExamManage examManage) {
        return this.baseMapper.insert(examManage);
    }

    @Override
    public List<ExamManage> selectEnable(Integer flag) {
        LambdaQueryWrapper<ExamManage> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ExamManage::getEnable,flag);
        return this.baseMapper.selectList(wrapper);
    }

    @Override
    public Integer updateEnable(Integer id,Integer flag) {
        LambdaUpdateWrapper<ExamManage> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(ExamManage::getId,id).set(ExamManage::getEnable,flag);
        return this.baseMapper.update(null,wrapper);
    }

    @Override
    public List<ExamManage> selectExam() {
        return this.baseMapper.selectList(null);
    }

    @Override
    public ExamManage selectExamOne(Integer id) {
        return this.baseMapper.selectById(id);
    }


    @Override
    public Page<ExamManage> selectExamPage(ExamManage examManage,Page<ExamManage> examManagePage) {
        LambdaQueryWrapper<ExamManage> wrapper = new LambdaQueryWrapper<>();
        // 根据科目，班级，年级，描述，禁用条件查询
        if(examManage.getSource()!=null){
            wrapper.eq(ExamManage::getSource,examManage.getSource());
        }
        if(examManage.getClassName()!=null){
            wrapper.eq(ExamManage::getClassName,examManage.getClassName());
        }
        if(examManage.getGrade()!=null){
            wrapper.eq(ExamManage::getGrade,examManage.getGrade());
        }
        if(examManage.getDescription()!=null){
            wrapper.like(ExamManage::getDescription,examManage.getDescription());
        }
        if(examManage.getEnable()!=null){
            wrapper.eq(ExamManage::getEnable,examManage.getEnable());
        }
        return this.baseMapper.selectPage(examManagePage,wrapper);
    }
    @Override
    public  Integer deleteExam(Integer id){
        return this.baseMapper.deleteById(id);

    }
    @Override
    public Integer updateExam(ExamManage examManage) {
        return this.baseMapper.updateById(examManage);
    }

    @Autowired
    private CourseDistributionService courseDistributionService;

    @Override
    public Integer updateOrInsertExam(ExamManage examManage){
        if(examManage.getCan()==2){
            examManage.setClassName(courseDistributionService.selectClassNameByCourseName(examManage.getSource()));
        }
        if(StrUtil.isBlank(String.valueOf(examManage.getId()))){
            // 没有传入ID直接插入数据
            return this.baseMapper.insert(examManage);
        }else{
            if(selectExamOne(examManage.getId()) == null){
                // 导入数据的ID没有与表中的ID重复则插入数据
                return this.baseMapper.insert(examManage);
            }else{
                // 传入的ID与表中已有的ID重复则更新数据
                return this.baseMapper.updateById(examManage);
            }
        }
    }

    @Override
    public Page<ExamManage> selectExamPage2(String userName,ExamRequest examRequest, Page<ExamManage> examManagePage) {
        return this.baseMapper.selectExamPage2(userName,examRequest,examManagePage);

    }

    @Override
    public Page<ExamManage> teachSelectExamPage(ExamRequest examRequest, Page<ExamManage> examManagePage) {
        return this.baseMapper.teachSelectExamPage(examRequest,examManagePage);
    }

    @Override
    public List<ScoreRequest> selectByExamId(String examId) {
        List<ScoreRequest> list = this.baseMapper.selectByExamId(examId);
        return list;
    }

    @Override
    public String seclctExamClass(String id) {
        return  this.baseMapper.seclctExamClass(id);
    }

    @Override
    public List<Admin> seclctExamStudent(String id) {
        List<Admin> list=this.baseMapper.seclctExamStudent(id);
        return list;
    }


    @Override
    public List<Admin> seclctStudentByclassName(String className) {
        return  this.baseMapper.seclctStudentByclassName(className);
    }

    @Autowired
    ExamManageMapper examManageMapper;
    @Autowired
    DeriveExcelService deriveExcelService;
    @Override
    public Map<String,Integer> selectNumByExamId(String examId) {
        Map<String, Integer> map = new HashMap<>();
        map.put("pass", 0);
        map.put("fail", 0);
        map.put("miss", 0);
        map.put("unread", 0);
        int good = examManageMapper.selectGoodByExamId(examId);
        int bad = examManageMapper.selectBadByExamId(examId);
        int miss;
        if (!deriveExcelService.select(Integer.parseInt(examId)).isEmpty() && deriveExcelService.select(Integer.parseInt(examId)).get(0).getCommitRole().equals("学生")) {
            int unfinished = examManageMapper.selectUnfinishedByExamId(examId);
            miss = examManageMapper.seclctExamStudent(examId).size() - good - bad - unfinished;
            map.put("pass", good);
            map.put("fail", bad);
            map.put("unread", unfinished);
            map.put("miss", miss);
        } else if (!deriveExcelService.select(Integer.parseInt(examId)).isEmpty()) {
            miss = examManageMapper.seclctExamStudent(examId).size() - good - bad;
            map.put("pass", good);
            map.put("fail", bad);
            map.put("miss", miss);
        }

        return map;
    }

    @Override
    public Map<String, List<StudentRequest>> selectStudentByExamId(String examId) {
        Map<String, List<StudentRequest>> map = new HashMap<>();
        List<StudentRequest> list1 = examManageMapper.selectGoodStudentByExamId(examId);
        List<StudentRequest> list2 = examManageMapper.selectBadStudentByExamId(examId);
        List<StudentRequest> list = new ArrayList<>();
        List<StudentRequest> list3 = new ArrayList<>();
        map.put("pass", list1);
        map.put("fail", list2);
        map.put("miss", list);
        map.put("unread", list3);
        if (!deriveExcelService.select(Integer.parseInt(examId)).isEmpty() && deriveExcelService.select(Integer.parseInt(examId)).get(0).getCommitRole().equals("学生")) {
            list3 = examManageMapper.selectUnfinishedStudentByExamId(examId);
            List<StudentRequest> list4 = examManageMapper.selectMissStudentByExamID(examId);
            map.put("unread", list3);
            map.put("miss", list4);
        } else if (!deriveExcelService.select(Integer.parseInt(examId)).isEmpty()) {
            list = examManageMapper.selectMissStudentByExamID2(examId);
            map.put("miss", list);
        }
        return map;
    }

    //学生提交试卷and更改考试状态
//    @Autowired
//    DeriveExcelService deriveExcelService;
    @Override
    public void updateExamState(Integer id, String examId, String userName, Boolean enable) {
       List<DeriveExcel> list=deriveExcelService.selectDeriveByExamIdAndUsername(examId,userName);
       for(DeriveExcel a:list){
           if(a.getId()==id){
               a.setEnable(enable);
              deriveExcelService.updateOrInsert(a);
           }else {
               a.setEnable(false);
               deriveExcelService.updateOrInsert(a);
           }
       }

    }

    @Override
    public Page<ExamManage> selectStudentOnlineExam(ExamManage examManage, Page<ExamManage> examManagePage) {
        LambdaQueryWrapper<ExamManage> wrapper = new LambdaQueryWrapper<>();
        // 根据科目，班级，年级，描述，禁用条件查询
        if(examManage.getSource()!=null){
            wrapper.like(ExamManage::getSource,examManage.getSource());
        }
        wrapper.isNotNull(ExamManage::getPaperId);
        return this.baseMapper.selectPage(examManagePage,wrapper);
    }

    @Autowired
    ExamManageService examManageService;

    @Override
    public void updateExamStateByTime() {
        List<ExamManage> list=examManageMapper.selectAll();
            for(ExamManage a:list){
                String creatTime=a.getExamDate();
                Integer time=a.getTotalTime();

                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                Date b = addDateMinute(creatTime, time);
                Date currentTime = new Date();
                Integer id=a.getId();
                if(b.getTime()<currentTime.getTime()){
                   examManageService.updateEnable(id,0);
                }
            }
    }


    public  Date addDateMinute(String day, int x) {
        //入参的格式
        // 24小时制
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try {
            date = format.parse(day);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        if (date == null){
            return null;
        }
//        System.out.println("front:" + format.format(date));
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        // 24小时制
        cal.add(Calendar.MINUTE, x);
        //得到结算后的结果 yyyy-MM-dd HH:mm
        date = cal.getTime();
//        System.out.println("after:" + format.format(date));
        cal = null;
        return date;
    }


}
